package com.qst.controller;

import com.qst.Constant;
import com.qst.ExamException;
import com.qst.entity.User;
import com.qst.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/password.action")
public class PasswordController {
    @Autowired
    @Qualifier("userServiceSsmImpl")
    private UserService userService;
    @GetMapping
    public String showChangePassword() {
        // 转发到password.jsp页面
        return "password";
    }
    @PostMapping
    public String changePassword(HttpSession session,String oldPassword,String newPassword,String comfirm, Model model) {
        User currentUser = (User) session.getAttribute(Constant.CURRENT_USER);

        if (!comfirm.equals(newPassword)) {
            model.addAttribute("error", "两次密码输入不一致");
            return "password";
        } else {
            try {
                userService.changePassword(currentUser.getId(), oldPassword, newPassword);
                model.addAttribute("message", "登录密码已更改，请退出重新登录");
                return "redirect:/passwordmsg.jsp";
            } catch (ExamException ex) {
                model.addAttribute("error", ex.getMessage());
                return "password";
            }
        }
    }

}
